package com.hmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.hmall.common.utils.AliyunOSSOperator;
import com.hmall.common.utils.UserContext;
import com.hmall.domain.po.Information;
import com.hmall.mapper.InformationMapper;
import com.hmall.service.IInformationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HBQ
 * @since 2025-10-22
 */
@Service
public class InformationServiceImpl extends ServiceImpl<InformationMapper, Information> implements IInformationService {

    @Autowired
    private InformationMapper informationMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;
    /**
     * 根据用户id查询信息（数据回显）
     */
    @Override
    public Information getByUserId(Long id) {
        LambdaQueryWrapper<Information> queryWrapper = new LambdaQueryWrapper<Information>();
        queryWrapper.eq(Information::getUserId, id);
        Information result = getOne(queryWrapper);
        return result;
    }

    /**
     * 保存信息
     */
    @Override
    public boolean saveByUserId(Information information) {
        LambdaQueryWrapper<Information> queryWrapper = new LambdaQueryWrapper<Information>();
        queryWrapper.eq(Information::getUserId, UserContext.getUser());
        Long Id = UserContext.getUser();


        informationMapper.saveUser(information,UserContext.getUser());
        return true;
    }

    /**
     * 修改更新 信息
     */
    @Override
    public boolean updateByUserId(Information information, MultipartFile  file) {
//        LambdaQueryWrapper<Information> userid = new LambdaQueryWrapper<Information>();
//        userid.eq(Information::getUserId, UserContext.getUser());
//        Long id= UserContext.getUser();
//        return informationMapper.updateInformation(information, file , userid);

        try {
            // 如果有上传新文件，则先上传到OSS
            if (file != null && !file.isEmpty()) {
                String imageUrl = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
                information.setImage(imageUrl); // 设置新的图片URL
            }

            // 更新用户信息
            LambdaQueryWrapper<Information> userid = new LambdaQueryWrapper<Information>();
            Long userId = UserContext.getUser();
//            userid.eq(Information::getUserId, UserContext.getUser());
            return informationMapper.saveUser(information, userId);
//            return update(information, userid);
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return false;
        }
    }
}
